package com.alibaba.sample.kantiezi.biz.admin.ao;

import com.alibaba.biz.command.ao.ApplicationObjectSupport;
import com.alibaba.biz.command.result.Result;
import com.alibaba.biz.command.result.ResultSupport;

import com.alibaba.common.lang.io.StreamUtil;

import com.alibaba.sample.kantiezi.biz.admin.result.AddProductResultCode;
import com.alibaba.sample.kantiezi.dal.dao.CategoryDao;
import com.alibaba.sample.kantiezi.dal.dao.ProductDao;
import com.alibaba.sample.kantiezi.dal.dataobject.Category;
import com.alibaba.sample.kantiezi.dal.dataobject.Product;

import com.alibaba.service.resource.ResourceLoaderService;
import com.alibaba.service.resource.ResourceOption;

import org.apache.commons.fileupload.FileItem;

import org.springframework.dao.DataIntegrityViolationException;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class AddProduct extends ApplicationObjectSupport {
    private ResourceLoaderService resourceLoaderService;
    private CategoryDao           categoryDao;
    private ProductDao            productDao;
    private String                categoryId;
    private Product               product;
    private FileItem              picture;

    public void setResourceLoaderService(ResourceLoaderService resourceLoaderService) {
        this.resourceLoaderService = resourceLoaderService;
    }

    public void setCategoryDao(CategoryDao categoryDao) {
        this.categoryDao = categoryDao;
    }

    public void setProductDao(ProductDao productDao) {
        this.productDao = productDao;
    }

    public void setCategoryId(String categoryId) {
        this.categoryId = categoryId;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public void setPicture(FileItem picture) {
        this.picture = picture;
    }

    public Result doGetCategory() {
        Category category = categoryDao.getCategoryById(categoryId);
        Result   result   = new ResultSupport();

        result.setDefaultModel(category);

        return result;
    }

    public Result doAdd() {
        Result result        = new ResultSupport();
        String imageFileName;

        try {
            imageFileName    = getPictureName();
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(AddProductResultCode.COULD_NOT_GET_UPLOAD_DIR);

            return result;
        }

        product.setLogo(imageFileName);
        product.setCategoryId(categoryId);

        try {
            productDao.insertProduct(product);
        } catch (DataIntegrityViolationException e) {
            result.setSuccess(false);
            result.setResultCode(AddProductResultCode.DUPLICATED_PRODUCT_ID);

            return result;
        }

        return result;
    }

    private String getPictureName() throws Exception {
        File uploadDir = resourceLoaderService.getResourceAsFile("/kantiezi/upload",
                                                                 ResourceOption.NEED_NOT_EXIST);

        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        if (!uploadDir.isDirectory()) {
            throw new IOException("Could not create directory " + uploadDir.getAbsolutePath());
        }

        String imageFileName = null;

        if (picture != null) {
            String fileName = picture.getName().replaceAll("\\", "/");

            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);

            String ext   = "";
            int    index = fileName.lastIndexOf(".");

            if (index > 0) {
                ext = fileName.substring(index);
            }

            InputStream  is = null;
            OutputStream os = null;

            try {
                File imageFile = File.createTempFile("image_", ext, uploadDir);

                imageFileName = imageFile.getName();

                is = picture.getInputStream();
                os = new BufferedOutputStream(new FileOutputStream(imageFile));

                StreamUtil.io(is, os);
            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                    }
                }

                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }
        }

        return imageFileName;
    }
}
